<?php

$sanitize_all_escapes = true;
$fake_register_globals = false;

require_once("../../globals.php");
require_once("$srcdir/patient.inc");
require_once("$srcdir/formdata.inc.php");
require_once("$srcdir/formatting.inc.php");
require_once("$srcdir/jsonwrapper/jsonwrapper.php");

// With the ColReorder or ColReorderWithResize plug-in, the expected column
// ordering may have been changed by the user.  So we cannot depend on
// list_options to provide that.
//
$aColumns = explode(',', $_GET['sColumns']);

 /*echo "<pre>";
  print_r($_SESSION);
  echo "</pre>"; */

$sql_fac = sqlQuery("SELECT facility_id FROM users_facility WHERE table_id =".$_SESSION['authUserID']);

$facility = $sql_fac['facility_id'];

// Paging parameters.  -1 means not applicable.
//
$iDisplayStart = isset($_GET['iDisplayStart']) ? 0 + $_GET['iDisplayStart'] : -1;
$iDisplayLength = isset($_GET['iDisplayLength']) ? 0 + $_GET['iDisplayLength'] : -1;
$limit = '';
if ($iDisplayStart >= 0 && $iDisplayLength >= 0) {
    $limit = " LIMIT $iDisplayStart, $iDisplayLength";
}

// Column sorting parameters.
//
$orderby = '';
if (isset($_GET['iSortCol_0'])) {
    for ($i = 0; $i < intval($_GET['iSortingCols']); ++$i) {
        $iSortCol = intval($_GET["iSortCol_$i"]);
        if ($_GET["bSortable_$iSortCol"] == "true") {
            $sSortDir = add_escape_custom($_GET["sSortDir_$i"]); // ASC or DESC
            // We are to sort on column # $iSortCol in direction $sSortDir.
            $orderby .= $orderby ? ', ' : ' ORDER BY ';
            //
            if ($aColumns[$iSortCol] == 'name') {
                $orderby .= "fname $sSortDir, mname $sSortDir, lname $sSortDir, lname2 $sSortDir ";
            } else {
                $orderby .= "`" . add_escape_custom($aColumns[$iSortCol]) . "` $sSortDir";
            }
        }
    }
}
//echo "o r d e r b y: ".$orderby; //ORDER BY fname asc, mname asc, lname asc, lname2 asc
// Global filtering.
//
$where = '';
if (isset($_GET['sSearch']) && $_GET['sSearch'] !== "") {
    $sSearch = add_escape_custom($_GET['sSearch']);
    foreach ($aColumns as $colname) {
        $where .= $where ? "OR " : "WHERE ( ";
        if ($colname == 'name') {
            $where .=
                    "fname LIKE '%$sSearch%' OR " .
                    "mname LIKE '%$sSearch%' OR " .
                    "lname LIKE '%$sSearch%' OR " .
                    "lname2 LIKE '%$sSearch%' ";
        } else {
            $where .= "`" . add_escape_custom($colname) . "` LIKE '%$sSearch%' ";
        }
    }
    if ($where)
        $where .= ")";
}

//echo "w h e r e: ".$where; //W H E R E: 1 = 1 AND ( lname LIKE '%david%' OR lname2 LIKE '%david%' OR fname LIKE '%david%' OR mname LIKE '%david%' )
// Column-specific filtering.
//
for ($i = 0; $i < count($aColumns); ++$i) {
    $colname = $aColumns[$i];
    if (isset($_GET["bSearchable_$i"]) && $_GET["bSearchable_$i"] == "true" && $_GET["sSearch_$i"] != '') {
        $where .= $where ? ' AND' : 'WHERE';
        $sSearch = add_escape_custom($_GET["sSearch_$i"]);
        if ($colname == 'name') {
            $where .= " ( " .
                    "lname LIKE '%$sSearch%' OR " .
                    "lname2 LIKE '%$sSearch%' OR " .
                    "fname LIKE '%$sSearch%' OR " .
                    "mname LIKE '%$sSearch%' )";
        } else {
            $where .= " `" . add_escape_custom($colname) . "` LIKE '$sSearch%'";
        }
    }
}

// Compute list of column names for SELECT clause.
// Always includes pid because we need it for row identification.
//
$sellist = 'DISTINCT(pat_data.pid)';
foreach ($aColumns as $colname) {
    if ($colname == 'pid')
        continue;
    $sellist .= ", ";
    if ($colname == 'name') {
        $sellist .= "fname, mname, lname, lname2";
    } else {
        $sellist .= "`" . add_escape_custom($colname) . "`";
    }
}

// Get total number of rows in the table.
//
if(acl_check('admin', 'spclt') ){
	
		$sql1 = "SELECT COUNT(DISTINCT(pat_data.pid)) AS count FROM patient_data pat_data  ";
		
	
}else{
	if ($where == '') {
		$sql1 = "SELECT COUNT(DISTINCT(pat_data.pid)) AS count FROM patient_data pat_data  
			left join patient_provider pat_prov on pat_prov.pid = pat_data.pid  
			left join patient_facility pat_fac on pat_fac.pid = pat_data.pid 
			where pat_prov.provider_id=" . $_SESSION['authUserID'] . " OR (pat_fac.facility_id=". $facility .")";
	} else {
		$sql1 = "SELECT COUNT(DISTINCT(pat_data.pid)) AS count FROM patient_data pat_data  
			left join patient_provider pat_prov on pat_prov.pid = pat_data.pid  
			left join patient_facility pat_fac on pat_fac.pid = pat_data.pid  
			where pat_prov.provider_id=" . $_SESSION['authUserID'] . " OR (pat_fac.facility_id=". $facility.")";
	}
}

//echo $sql1;

$iTotal = 0;
$row = sqlQuery($sql1);
$iTotal = $row['count'];

//echo "dfdfd: ".$iTotal;
// Get total number of rows in the table after filtering.
if(acl_check('admin', 'spclt') ){
	if ($where == '') {
		$queryi = "SELECT COUNT(DISTINCT(pat_data.pid)) AS count FROM patient_data pat_data  ";
		$row = sqlQuery($queryi);
	} else {
		$queryi = "SELECT COUNT(DISTINCT(pat_data.pid)) AS count FROM patient_data pat_data $where  " ;
		$row = sqlQuery($queryi);
	}
}else{
	if ($where == '') {
		$queryi = "SELECT COUNT(DISTINCT(pat_data.pid)) AS count FROM patient_data pat_data  
					left join patient_facility pat_fac on pat_fac.pid = pat_data.pid  
					where pat_fac.facility_id=". $facility;
		$row = sqlQuery($queryi);
	} else {
		$queryi = "SELECT COUNT(DISTINCT(pat_data.pid)) AS count FROM patient_data pat_data  
					left join patient_facility pat_fac on pat_fac.pid = pat_data.pid " .
				$where . " and pat_fac.facility_id=".$facility;
		$row = sqlQuery($queryi);
	}
}

//echo $queryi;

$iFilteredTotal = $row['count'];


// Build the output data array.
//
$out = array(
    "sEcho" => intval($_GET['sEcho']),
    "iTotalRecords" => $iTotal,
    "iTotalDisplayRecords" => $iFilteredTotal,
    "aaData" => array()
);

$joindata = " 
                left join patient_facility pat_fac on pat_fac.pid = pat_data.pid  ";

if ($where == '') {
    $joinwhere = " where pat_fac.facility_id=". $facility;
} else {
    $joinwhere = " and   pat_fac.facility_id=". $facility;
}

if(acl_check('admin', 'spclt') ){
    $query = "SELECT $sellist, phone_contact FROM patient_data pat_data where 1 ".  $orderby . $limit;
}else{
    $query = "SELECT $sellist, phone_contact FROM patient_data pat_data " . $joindata . $where . $joinwhere . $orderby . $limit;
}
//echo $query;




//echo "Q U E R Y:".$query;

$res = sqlStatement($query);
if( $iFilteredTotal > 0){
    while ($row = sqlFetchArray($res)) {
        // Each <tr> will have an ID identifying the patient.
        $arow = array('DT_RowId' => 'pid_' . $row['pid']);
        foreach ($aColumns as $colname) {
            if ($colname == 'name') {
                $name = "";
                if ($row['fname'])
                    $name = $row['fname'];
                if ($row['mname'])
                    $name .= ' ' . $row['mname'];
                //if ($name && $row['fname']) $name .= ', ';
                $name .= ' ' . $row['lname'] . " " . $row['lname2'];
                $arow[] = $name;
            }
            else if ($colname == 'DOB' || $colname == 'regdate' || $colname == 'ad_reviewed' || $colname == 'userdate1') {
                $arow[] = oeFormatShortDate($row[$colname]);
            } else if ($colname == 'sex'){

                $arow[] = xl($row[$colname]);
            }else {
                $arow[] = $row[$colname];
            }
        }
        $out['aaData'][] = $arow;
    }
}else{
    $out = array(
    "sEcho" => intval($_GET['sEcho']),
    "iTotalRecords" => 0,
    "iTotalDisplayRecords" => 0,
    "aaData" => array()
);
    
}

// error_log($query); // debugging
// Dump the output array as JSON.
//
echo json_encode($out);
?>
